package com.example.guiguihomemedical.service.impl;

import com.example.guiguihomemedical.common.FileUploadResult;
import com.example.guiguihomemedical.entity.*;
import com.example.guiguihomemedical.entity.dto.*;
import com.example.guiguihomemedical.mapper.*;
import com.example.guiguihomemedical.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.transaction.Transactional;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SigningServiceImpl implements SigningService {
    private static final Logger logger = LoggerFactory.getLogger(SigningServiceImpl.class);
    @Autowired
    private SigningMapper signingMapper;
    @Autowired
    private ServicesigningMapper servicesigningMapper;
    @Autowired
    private FulfillmentMapper fulfillmentMapper;
    @Autowired
    private FamilyarChivesService familyarChivesService;
    @Autowired
    private FileUploadService fileUploadService;
    @Autowired
    private DoctorService doctorService;
    @Autowired
    private RecordListMapper recordListMapper;
    @Autowired
    private RecordSearchService recordSearchService;
    @Autowired
    private RecordMapper recordMapper;
    @Autowired
    private ServiceitemsMapper serviceitemsMapper;
    @Autowired
    private FollowUpMapper followUpMapper;

    @Autowired
    private ServicepackMapper servicepackMapper;
    private final SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
    private final SimpleDateFormat dateFormat2 = new SimpleDateFormat("yyyy-MM-dd");

    @Override
    public void delete(String id) {
        signingMapper.delete(id);
    }

    @Transactional
    @Override
    public void deleteTrueId(int id) {
        Signing signing = signingMapper.getByTrueId(id);
        fulfillmentMapper.deleteTrueId(id);
        followUpMapper.deleteByIdCard(signing.getIdcard());
        servicesigningMapper.deleteBySigningId(id);
        signingMapper.deleteTrueId(id);
    }

    @Override
    public void add(Signing signing) {
        signing.setStarttime(new Date());
        signingMapper.insert(signing);
    }

    @Transactional
    @Override
    public void addAll(SigningAdd signingAdd, MultipartFile uploadFile, List<Servicepack> servicepackList) throws ParseException {
        Signing signing = new Signing();
        FileUploadResult fileUploadResult = fileUploadService.upload(uploadFile);
        signing.setServicebook(fileUploadResult.getImgurl());
        Date starttime = dateFormat.parse(signingAdd.getStarttime() + " 00:00:00");
        signing.setStarttime(starttime);
        Date endtime = dateFormat.parse(signingAdd.getEndtime() + " 00:00:00");
        signing.setEndtime(endtime);
        signing.setDoctorid(signingAdd.getDoctorid());
        signing.setIdcard(signingAdd.getIdcard());
        signingMapper.insert(signing);
        Signing signingid = signingMapper.getByTimeServing(starttime, endtime, signing.getIdcard());
        for (Servicepack servicepack : servicepackList) {
            Servicesigning servicesigning = new Servicesigning();
            servicesigning.setServiceid(servicepack.getId());
            servicesigning.setIdcard(signingAdd.getIdcard());
            servicesigning.setSigningid(signingid.getId());
            servicesigningMapper.insert(servicesigning);
        }
    }

    @Override
    public void update(Signing signing) {
        signingMapper.update(signing);
    }

    @Override
    public List<Signing> getAll() {
        return signingMapper.getAll();
    }

    @Transactional
    @Override
    public void addFamilySigningAll(MultipartFile uploadFile, List<FamilyarChooseService> familyarChooseServiceList, String staTime, String endTime, String doctorId) throws ParseException {
        for (FamilyarChooseService familyarChooseService : familyarChooseServiceList) {
            Signing signing = new Signing();
            Date starttime = dateFormat.parse(staTime + " 00:00:00");
            signing.setStarttime(starttime);
            Date endtime = dateFormat.parse(endTime + " 00:00:00");
            signing.setEndtime(endtime);
            signing.setType("1");
            FileUploadResult fileUploadResult = fileUploadService.upload(uploadFile);
            signing.setServicebook(fileUploadResult.getImgurl());
            signing.setDoctorid(Integer.valueOf(doctorId));
            signing.setIdcard(familyarChooseService.getIdcard());
            signingMapper.insert(signing);
            Record record = recordMapper.findByIdcard(familyarChooseService.getIdcard());
            if (record.getType().equals("1")) {
                recordMapper.updateRecordType(familyarChooseService.getIdcard(), "2");
            }
            Signing signingid = signingMapper.getByIdcardNowServing(signing.getIdcard());
            for (Servicepack servicepack : familyarChooseService.getServicePackageResponseList()) {
                Servicesigning servicesigning = new Servicesigning();
                servicesigning.setServiceid(servicepack.getId());
                servicesigning.setIdcard(familyarChooseService.getIdcard());
                servicesigning.setSigningid(signingid.getId());
                servicesigningMapper.insert(servicesigning);
            }
        }
    }

    @Override
    public List<Signing> getAllstate(String IdCard, String staTime, String endTime) throws ParseException {
        List<Signing> signingList = signingMapper.getAllByIdCard(IdCard);
        if (staTime != "" && endTime != "") {
            Date date1 = dateFormat2.parse(staTime);
            Date date2 = dateFormat2.parse(endTime);
            List<Signing> filteredList = signingList.stream()
                    .filter(signing -> {
                        Date startTime2 = signing.getStarttime();
                        Date endTime2 = signing.getEndtime();
                        return (startTime2 != null && endTime2 != null) &&
                                (date1 == null || endTime2.after(date1)) &&
                                (date2 == null || startTime2.before(date2));
                    })
                    .collect(Collectors.toList());
            return filteredList;
        } else {
            return signingList;
        }
    }

    @Override
    public Signingdetail getSigningdetail(int signingId) {
        Signing signing = signingMapper.getByTrueId(signingId);
        FamilyarChivesList familyarChivesList = familyarChivesService.findByIdCardAllFamilyList(signing.getIdcard());
        List<FamilySigningdetail> familySigningdetailList = new ArrayList<>();
        Doctor doctor = doctorService.findByDoctorId(signing.getDoctorid());
        for (FamilyarChivesRecordList familyarChivesRecordList : familyarChivesList.getFamilyMembers()) {
            List<String> ServicePackName = new ArrayList<>();
            List<String> listenerNames = recordListMapper.getListenerNamesById(familyarChivesRecordList.getIdcard());
            Signing signing1 = signingMapper.getByTimeServing(signing.getStarttime(), signing.getEndtime(), familyarChivesRecordList.getIdcard());
            List<Servicesigning> servicesigningList = servicesigningMapper.getByIdcardAll(familyarChivesRecordList.getIdcard(), signing1.getId());
            for (Servicesigning servicesigning : servicesigningList) {
                Servicepack servicepack = servicepackMapper.getById(servicesigning.getServiceid());
                ServicePackName.add(servicepack.getName());
            }
            FamilySigningdetail familySigningdetail = new FamilySigningdetail(
                    familyarChivesRecordList.getIdcard(),
                    familyarChivesRecordList.getName(),
                    listenerNames,
                    ServicePackName
            );
            familySigningdetailList.add(familySigningdetail);
        }
        Signingdetail signingdetail = new Signingdetail(
                familyarChivesList.getHouseholdId(),
                familyarChivesList.getHouseholdName(),
                familyarChivesList.getHomeAddress(),
                familyarChivesList.getHouseholdPhone(),
                signing.getServicebook(),
                doctor.getOrganization(),
                doctor.getName(),
                familySigningdetailList
        );
        return signingdetail;
    }

    @Override
    public List<List<RecordList>> SearchFamilySigningAll(List<FamilyarChooseService> familyarChooseServiceList, String staTime, String endTime) throws ParseException {
        List<List<RecordList>> recordList = new ArrayList<>();
        for (FamilyarChooseService familyarChooseService : familyarChooseServiceList) {
            Signing signing1 = signingMapper.getByIdOrserByendtime(familyarChooseService.getIdcard());
            RecordSearch recordSearch = new RecordSearch(
                    -1,
                    "-1",
                    -1,
                    familyarChooseService.getIdcard(),
                    new ArrayList<>()
            );
            Signing signing = new Signing();
            Date starttime = dateFormat.parse(staTime + " 00:00:00");
            signing.setStarttime(starttime);
            Date endtime = dateFormat.parse(endTime + " 00:00:00");
            signing.setEndtime(endtime);
            if (starttime.compareTo(signing1.getEndtime()) < 0) {
                recordList.add(recordSearchService.searchRecord(recordSearch));
            }
        }
        return recordList;
    }

    @Override
    public Signing getById(String id) {
        return signingMapper.getById(id);
    }

    @Override
    public List<Record> getRecordByNowServing() {
        List<Signing> signingList = signingMapper.getByNowServing();
        List<Record> recordList = new ArrayList<>();
        for (int i = 0; i < signingList.size(); i++) {
            recordList.add(signingMapper.getRecordByIdcard(signingList.get(i).getIdcard()));
        }
        return recordList;
    }

    @Override
    public List<Record> searchRecordByNowServing(Integer PageBegin, Integer PageSize, String searchString) {

        if (PageBegin == null) {
            PageBegin = 0;
        }
        if (PageSize == null) {
            PageSize = 10;
        }
        return signingMapper.searchNowServingRecord(PageBegin, PageSize, searchString);
    }

    @Override
    public Signing getByIdOrserByendtime(String id) {
        return signingMapper.getByIdOrserByendtime(id);
    }

    @Override
    public Signing getByIdcardNowServing(String idcard) {
        return signingMapper.getByIdcardNowServing(idcard);
    }

}
